package com.efesco.logQuery;

import java.util.List;

import com.bstek.dorado.data.*;
import com.bstek.dorado.data.db.AutoDBField;
import com.bstek.dorado.data.db.DBStatement;
import com.bstek.dorado.data.db.SqlDataset;
import com.bstek.dorado.utils.variant.VariantSet;
import com.bstek.dorado.view.data.ViewBaseField;
import com.bstek.dorado.common.*;
import com.efesco.common.CommUtil;

/**
 * query_dataset_resultListener
 */
public class query_dataset_resultListener extends AbstractDatasetListener {

	public void onInit(Dataset dataset) throws Exception {
		// System.out.println("---------------");
		DoradoContext context = DoradoContext.getContext();
		SqlDataset dsr = (SqlDataset) dataset;
		parseSql ps = new parseSql();
		DBStatement dbs = new DBStatement();
		String logQueryId = context.getParameter("logquery_id");
		if (logQueryId != null) {

			dbs.setSql("select lq.* from s_log_query lq where lq.LOGQUERY_ID="
					+ logQueryId);
			VariantSet vs = dbs.query();
			ps.setSentence(vs.getString("SQL"));
			ps.init();
			for (int i = 0; i < ps.getField().length; i++) {
				String fieldNmae=ps.getField()[i].split("\\.")[1];
				AutoDBField field = (AutoDBField) dataset.addField(fieldNmae);
				field.setLabel(ps.getField()[++i]);
				if(fieldNmae.toLowerCase().indexOf("date")>-1||fieldNmae.toLowerCase().indexOf("time")>-1)
				field.setDataType(12);
			}
			dsr.setSql(ps.getSql());

			dbs.setSql("select lqc.* from s_log_query lq,s_log_query_condition lqc where lq.logquery_id=lqc.logquery_id and lqc.LOGQUERY_ID="
							+ logQueryId);
			List list = dbs.queryForList();
			for (int i = 0; i < list.size(); i++) {
				VariantSet record = (VariantSet) list.get(i);
					dsr.parameters().setString(
							record.getString("FIELD_DB") + ":"
									+ record.getString("FIELD_EN") + "["
									+ record.getString("FIELD_OPERATE") + "]", "");
			}
		}
		dbs.close();
	}

	public boolean beforeLoadData(Dataset dataset) throws Exception {
		SqlDataset ds = (SqlDataset) dataset;
		parseSql ps = new parseSql();
		DBStatement dbs = new DBStatement();

		String logQueryId = ds.parameters().getString("logquery_id");
		dbs.setSql("select lq.* from s_log_query lq where lq.LOGQUERY_ID="
				+ logQueryId);
		VariantSet vs = dbs.query();
		ps.setSentence(vs.getString("SQL"));
		ps.init();
		String sql=ps.getSql()+" ";
		dbs.setSql("select lqc.* from s_log_query lq,s_log_query_condition lqc where lq.logquery_id=lqc.logquery_id and lqc.LOGQUERY_ID="
				+ logQueryId);
		List list = dbs.queryForList();
		sql += ps.setConditionSQL(list,ds);
		
		ds.setSql(sql);

		return true;
	}

	public void afterLoadData(Dataset dataset) throws Exception {

	}

}
